<?php
if(!session_id()) session_start();

class CDataToken {
	const STORE_KEY = '_data_token_';
	const EXPIRE_TIME = 360; # s
	
	public static function genToken() {
		self::flush();
		$token = uniqid();
		return $token;
	}
	
	public static function dataIsValid($data) {
		$token = self::getDataToken($data);
		if($token && !isset($_SESSION[self::STORE_KEY][$token])) {
			return true;
		} else {
			return false;
		}
	}
	
	public static function setDataParams($data, $params) {
		$token = self::getDataToken($data);
		if(isset($_SESSION[self::STORE_KEY][$token])) {
			$_SESSION[self::STORE_KEY][$token]['params'] = $params;
		}
	}
	
	public static function getDataToken($data) {
		if(isset($data[self::STORE_KEY])) {
			$token = $data[self::STORE_KEY];
			return $token;
		}
		return null;
	}
	
	public static function useData($data, $params = array()) {
		$token = self::getDataToken($data);
		if(self::dataIsValid($data)) {
			$_SESSION[self::STORE_KEY][$token] = array(
				'used' => mktime(),
				'params' => $params,
			);
			return true;
		}
		return false;
	}
	
	public static function getDataParams($data) {
		if(isset($data[self::STORE_KEY])) {
			$token = $data[self::STORE_KEY];
			if(isset($_SESSION[self::STORE_KEY][$token]))
				return $_SESSION[self::STORE_KEY][$token]['params'];
		}
		return array();
	}
	
	public static function flush() {
		$time = mktime();
		if(isset($_SESSION[self::STORE_KEY])) {
			foreach($_SESSION[self::STORE_KEY] as $k=>$v) {
				if($time>=$v['used']+self::EXPIRE_TIME) 
					unset($_SESSION[self::STORE_KEY][$k]);
			}
		}
	}

}

?>